import io

import Uidput
import qrcode
import dbutils
import urllib.parse


def ORdata(user_name, user_email, request):
    # 获取用户信息
    user_uid = Uidput.generate_coffeeuid()
    #    data = {'html':'https://qiku.edu','name': user_name, 'email': user_email, 'uid': user_uid}
    base_url = f'{request.scheme}://{request.host}/QR'
    params = {'name': user_name, 'email': user_email, 'uid': user_uid}
    url = f"{base_url}?{urllib.parse.urlencode(params)}"

    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=10,
        border=4,
    )
    qr.add_data(url)
    qr.make(fit=True)

    conn2 = dbutils.connect_db(user="root", passwd="qiku-root", db="db")
    with conn2.cursor() as cursor:
        cursor.execute("INSERT INTO coffeevdata(uid,email,username, create_time) VALUES (%s, %s, %s, now())", (user_uid, user_email, user_name))
        pk = cursor.lastrowid

    img = qr.make_image(background='#ffffff')
    buffered = io.BytesIO()
    img.save(buffered, format="PNG")
    buffered.seek(0)
    return str(pk), buffered
